package main

import (
	"errors"
	"fmt"
	"net"
	"net/rpc"
	"os"
	"time"
)

type Args struct {
	A, B int
}
type Quotient struct {
	Quo, Rem int
}
type Arith int

func (t *Arith) Multiply(args *Args, reply *int) error {
	*reply = args.A * args.B
	return nil
}
func (t *Arith) Divide(args *Args, quo *Quotient) error {
	if args.B == 0 {
		return errors.New("divide by zero")
	}
	quo.Quo = args.A / args.B
	quo.Rem = args.A % args.B
	return nil
}

func CheckError(err error) {
	if err != nil {
		fmt.Println("error:", err.Error())
		os.Exit(1)
	}
}

// server.go
func main() {
	arith := new(Arith)
	rpc.Register(arith)
	tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
	CheckError(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	CheckError(err)

	for {
		// for loop
		fmt.Printf("accept time: %v\n", time.Now())
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		fmt.Printf("get client time: %v \n", time.Now())
		// 并发开启多个连接
		go rpc.ServeConn(conn)
	}

}
